package designMode.compositePattern;

import stack.Stack;

import java.util.Iterator;

/**
 * @author LIBOFEI
 * @ClassName CompositeIterator
 * @description
 * @date 2020/6/28 14:38
 * @Version 1.0
 **/
public class CompositeIterator implements Iterator {

    Stack<Iterator> stack = new Stack<>();

    public CompositeIterator(Iterator<MenuComponent> iterator){
        stack.push(iterator);
    }

    @Override
    public boolean hasNext() {
        if(stack.isEmpty()){
            return false;
        }else{
            Iterator<MenuComponent> iterator = stack.peek();
            if(!iterator.hasNext()){
                stack.pop();
                return hasNext();
            }else{
                return true;
            }
        }
    }

    @Override
    public Object next() {
        if(hasNext()){
            Iterator<MenuComponent> iterator = stack.peek();
            MenuComponent menuComponent = iterator.next();
            if(menuComponent instanceof Menu){
                stack.push(menuComponent.createIterator());
            }
            return menuComponent;
        }else{
            return null;
        }
    }

    @Override
    public void remove() {
        throw  new UnsupportedOperationException();
    }
}
